import React, { Component } from 'react';
import styles from './PutThread.scss';
import { observable, action, computed } from 'mobx';
import { observer } from 'mobx-react';

import initView from '@/cross/components/View';
const View = initView(styles);
import initText from '@/cross/components/Text';
const Text = initText(styles);
import initImage from '@/cross/components/Image';
const Image = initImage(styles);
import initScrollView from '@/cross/components/ScrollView';
const ScrollView = initScrollView(styles);
import initImageBackground from '@/cross/components/ImageBackground';
const ImageBackground = initImageBackground(styles);

import { Page, HeaderBar, Button, Modal, AutoList, SafeView } from '@/cross/components';
import { CrossPageProps } from '@/cross/pages/PropType';
import { TextInput } from '@/cross/components/Form/FormWidget';
import { Textarea } from '@tarojs/components';
import { px } from '@/components/mengti-ui/react-native';
import { Icon } from '@/cross/components/Icon';
import { $actionSheet, $service, $src, $toast, $uploadImage, $uploadVideo } from '@/cross/utils';
import { Video } from '@tarojs/components';
import VideoPlayer from '@/cross/components/Video';

export interface IPutThreadPageProps extends CrossPageProps {
  params: {};
}

interface ISimpleRichTextItem {
  /**
   * 内容类型
   * @enum 1 文字
   * @enum 2 图片
   * @enum 3 视频
   */
  t: 1 | 2 | 3;
  /* 内容 */
  c: string;
  w?: number;
  h?: number;
}

@observer
class PageView extends Component<IPutThreadPageProps> {
  @observable uploadProgress = 0;
  @observable form = {
    title: '',
  };
  @observable data: ISimpleRichTextItem[] = [{ t: 1, c: '' }];
  @computed get canSubmit() {
    let title = this.form.title;
    if (!title) return false;
    let data = this.data;
    let canSubmit = false;
    data.forEach((item) => {
      if (item.c) canSubmit = true;
    });
    return canSubmit;
  }
  @action add = (type: 1 | 2 | 3) => {
    if (type === 1) {
      this.data.push({ t: 1, c: '' });
    }
    if (type === 2) {
      $uploadImage({
        count: 9,
        onProgress: ({ progress }) => {
          this.uploadProgress = progress;
        },
      })
        .then(({ files }) => {
          this.data = this.data.concat(
            files.map((item) => ({
              t: 2,
              c: item.hash,
            })),
          );
          this.uploadProgress = 0;
        })
        .catch((e) => {
          console.log('[uploadImage error] ', e);
        });
    }
    if (type === 3) {
      $uploadVideo({
        sourceType: 'auto',
        onProgress: ({ progress }) => {
          this.uploadProgress = progress;
        },
      })
        .then(({ files }) => {
          console.log('[files] ', files);
          this.data = this.data.concat(
            files.map((item) => ({
              t: 3,
              c: item.hash,
              w: item.width,
              h: item.height,
            })),
          );
          this.uploadProgress = 0;
        })
        .catch(() => {});
    }
  };
  onClickMore = (item: ISimpleRichTextItem, i: number) => {
    $actionSheet(['删除', '取消'].filter((item) => !!item)).then((index) => {
      if (index === 0) {
        if (this.data.length === 1) return $toast('内容不可为空');
        this.data.splice(i, 1);
      }
    });
  };

  @action
  handleInputChange = (type: 'title' | 'item', index: number, value: any) => {
    if (type === 'title') {
      this.form = {
        ...this.form,
        title: value,
      };
    }
    if (type === 'item' && value.detail) {
      this.data[index] = {
        ...this.data[index],
        c: value.detail.value,
      };
    }
  };

  submit = () => {
    const form = this.form;
    $service('sns_thread', 'put', {
      type: 1,
      title: form.title,
      content: JSON.stringify(this.data),
    })
      .then(() => {
        $toast('已发布');
      })
      .catch((e) => {
        e?.errmsg && $toast(e.errmsg);
      });
  };

  render() {
    const canSubmit = this.canSubmit;
    return (
      <Page statusBarMode="dark" className="M-b-c-w put-thread">
        <View className="M-bd-b">
          <HeaderBar
            title="发布主题"
            titleAlign="left"
            mode="light"
            leftContent={null}
            rightContent={
              <View onClick={this.submit} className="M-p-h-b-10 M-p-v-b-5">
                <Text className={`M-f-s-16 M-f-c-${canSubmit ? '333' : '999'}`}>发布</Text>
              </View>
            }
            showBack
          />
        </View>
        <ScrollView>
          <View className="M-p-h-b-15">
            <View className="M-bd-b M-p-v-b-15">
              <TextInput
                placeholder="请输入标题(5-30个字)"
                inputStyle={{ fontSize: px(36) }}
                value={this.form.title}
                onChange={this.handleInputChange.bind(this, 'title', 0)}
              />
            </View>
          </View>
          <View className="M-p-h-b-15 M-p-b-10" style={{ minHeight: px(500) }}>
            {this.data.map((item, index) => {
              return (
                <View className="put-thread__item M-m-t-10" key={index}>
                  {item.t === 1 && (
                    <Textarea
                      type="text"
                      placeholder={index === 0 ? '请输入正文' : '请输入文字'}
                      autoHeight
                      maxlength={500000}
                      style={
                        {
                          fontSize: px(32),
                          lineHeight: px(42),
                          ...(index === this.data.length - 1
                            ? { minHeight: px(500), textAlignVertical: 'top' }
                            : {}),
                        } as any
                      }
                      value={item.c}
                      onChange={this.handleInputChange.bind(this, 'item', index)}
                    />
                  )}
                  {item.t === 2 && <Image fit src={$src(item.c)} />}
                  {item.t === 3 && (
                    <Video
                      src={$src(item.c, { source: true })}
                      autoplay
                      poster={$src(item.c, { source: true }) + '?vframe/jpg/offset/1'}
                      // initialTime='0'
                      loop={false}
                      muted={false}
                    />
                  )}
                  <View
                    onClick={this.onClickMore.bind(this, item, index)}
                    className="put-thread__item__btn M-center-all"
                  >
                    <Icon name="mtcaozuo" theme="dark" />
                  </View>
                </View>
              );
            })}
          </View>
          <View className="M-p-15">
            <View className="put-thread__add M-flexbox-horizontal">
              <View onClick={this.add.bind(this, 1)} className="M-flex-item M-center-all M-bd-r">
                <Text style={{ fontSize: px(28), color: '#666' }}>添加文字片段</Text>
              </View>
              <View onClick={this.add.bind(this, 2)} className="M-flex-item M-center-all M-bd-r">
                <Text style={{ fontSize: px(28), color: '#666' }}>添加图片</Text>
              </View>
              <View onClick={this.add.bind(this, 3)} className="M-flex-item M-center-all">
                <Text style={{ fontSize: px(28), color: '#666' }}>添加视频</Text>
              </View>
            </View>
          </View>
          <SafeView forceInset={{ top: 'never', bottom: 'always' }} />
        </ScrollView>
        {/* 上传进度 */}
        {this.uploadProgress > 0 && (
          <View
            className="M-b-c-1"
            style={{ position: 'absolute', bottom: 0, left: 0, width: '100%' }}
          >
            <View className="M-center-all M-p-v-b-10">
              <Text className="M-f-s-12 M-f-c-fff">{this.uploadProgress}%</Text>
            </View>
            <SafeView forceInset={{ top: 'never', bottom: 'always' }} />
          </View>
        )}
      </Page>
    );
  }
}

export default PageView;
